package org.opens.javaskill.thread.threadPool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import cn.hutool.core.thread.NamedThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

@Slf4j
public class ThreadPoolExecutorConfig {

    public static ThreadPoolExecutor threadPoolExecutor = null;

    /**
     * 获取线程池对象
     */
    public static ThreadPoolExecutor getInstance() {
        if (threadPoolExecutor != null) {
            return threadPoolExecutor;
        }

        synchronized (ThreadPoolExecutorConfig.class) {
            if (threadPoolExecutor != null) {
                return threadPoolExecutor;
            }

            initThreadPool();

            return threadPoolExecutor;
        }
    }

    /**
     * 初始化线程池
     */
    private static void initThreadPool() {
        // 使用spring提供的线程池自定义类
        ThreadFactory springThreadFactory = new CustomizableThreadFactory("full-query-");
        // 拒绝策略: 任务队列满之后直接丢弃任务并抛出异常
        threadPoolExecutor = new ThreadPoolExecutor(
                30,
                50,
                5,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(300),
                springThreadFactory,
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    /**
     * 打印线程池信息
     */
    public static void printThreadPoolInfo() {
        if (threadPoolExecutor == null) {
            log.info("线程池未初始化!");
            return;
        }

        int activeCount = threadPoolExecutor.getActiveCount();
        long completeTaskCount = threadPoolExecutor.getCompletedTaskCount();
        int poolSize = threadPoolExecutor.getPoolSize();
        long taskCount = threadPoolExecutor.getTaskCount();
        long largestPoolSize = threadPoolExecutor.getLargestPoolSize();
        long maximumPoolSize = threadPoolExecutor.getMaximumPoolSize();
        log.info("-->>外围线程池中的参数：activeCount:"+activeCount+",completeTaskCount:"+completeTaskCount+",poolSize:"+poolSize+",taskCount:"+taskCount+",largetPoolSize:"+largestPoolSize+",marximumPoolSize:"+maximumPoolSize);
    }

}